package ru.diagram.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;

@SuppressLint("DrawAllocation")
public class dHScrollbar extends dView {
	Paint paint;
	
	private int index = 0;
	private int max = 20;
	
	private OnResetIndexListener onResetIndexListener;

	public dHScrollbar(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		
		paint = new Paint();
	}
	
    @Override
    public void onDraw(Canvas canvas) {
    	
    	Rect r = getRect();
    	
    	paint.setStyle(Paint.Style.STROKE);
    	paint.setColor(0xFF888888);
    	paint.setTextSize(10);
    	
    	int center = r.bottom / 2;
    	int nw = (int)(r.height() * 0.12);
    	canvas.drawLine(r.left, center, r.right, center, paint);
    	
    	float step = r.width() / (float)max;
    	for (int i=0; i<=max; i++) {
    		float x = r.left + (float)i * step;
    		String l = getLabel(i);
    		
    		canvas.drawLine(x, center - nw, x, center + nw, paint);
    		
    		Rect bt = new Rect();
			paint.getTextBounds(l, 0, l.length(), bt);
    		canvas.drawText(l, x - bt.width() / 2, center + nw + bt.height(), paint);
    	}
    	
    	paint.setStyle(Paint.Style.FILL_AND_STROKE);
    	paint.setColor(0xFF333333);
    	
    	float ic = (float)index * step;
    	float isize = center - r.top;
    	Path path = new Path();
    	path.moveTo(r.left + ic - isize / 2, r.top);
    	path.lineTo(r.left + ic + isize / 2, r.top);
    	path.lineTo(r.left + ic, r.top + isize);
    	
    	canvas.drawPath(path, paint);
    }
    
    protected String getLabel(int a_index) {
    	return String.valueOf(a_index);
    }
    
    public void setOnResetIndexListener(OnResetIndexListener a_onResetIndexListener) {
    	onResetIndexListener = a_onResetIndexListener;
    }
    
    public void setMax(int a_max) {
    	if (max != a_max) {
    		max = a_max;
    		if (max < index) setIndex(a_max);
    		else this.postInvalidate();
    	}    	
    }
    
    public void setIndex(int a_index) {
    	
    	if (a_index < 0) a_index = 0;
    	else if (a_index > max) a_index = max;
    	
    	if (index != a_index) {
    		index = a_index;
        	this.postInvalidate();
        	if (onResetIndexListener != null) onResetIndexListener.onResetIndexEvent(index);
    	}
    }
    
 //@Owerride
	protected Rect getRect() {
		Rect r = new Rect(0, 0, getWidth(), getHeight());
		r.left = r.bottom / 2;
		r.right -= r.left;
		return r;
	}    
    
    public boolean onTouchEvent(MotionEvent event) {
    	Rect r = getRect();
        setIndex((int)((event.getX(0) - r.left) / r.width() * max));
		return true;
    }
}
